<template>
  <div class="vip-management">
    <!-- 头部 -->
    <div class="header">
      <div class="header-left">
        <button class="back-btn" @click="goBack">
          <i class="fas fa-arrow-left"></i>
        </button>
        <h2>VIP等级管理</h2>
      </div>
      <button class="add-btn" @click="handleAddLevel">
        <i class="fas fa-plus"></i>
        新增等级
      </button>
    </div>

    <!-- VIP等级列表 -->
    <div class="levels-container">
      <div class="loading" v-if="loading">
        <i class="fas fa-spinner fa-spin"></i>
        <p>加载中...</p>
      </div>

      <div class="levels-list" v-else>
        <div v-if="levels.length === 0" class="empty-state">
          <i class="fas fa-crown"></i>
          <p>暂无VIP等级</p>
          <button class="init-btn" @click="initializeLevels">
            <i class="fas fa-magic"></i>
            初始化默认等级
          </button>
        </div>

        <div v-for="level in levels" :key="level.id" class="level-card">
          <div class="level-content">
            <div class="level-header">
              <div class="level-badge" :class="'level-' + level.level">
                <i class="fas fa-crown"></i>
                <span>{{ level.name }}</span>
              </div>
              <div class="level-number">等级 {{ level.level }}</div>
            </div>
            <div class="level-details">
              <div class="detail-row">
                <div class="detail-item">
                  <span class="label">累计消费:</span>
                  <span class="value">{{ level.minTotalConsumption }} 元</span>
                </div>
                <div class="detail-item">
                  <span class="label">累计充值:</span>
                  <span class="value">{{ level.minTotalRecharge }} 元</span>
                </div>
              </div>
              <div class="detail-row">
                <div class="detail-item">
                  <span class="label">优先级:</span>
                  <span class="value">{{ level.priority }}</span>
                </div>
              </div>
              <div class="privileges">
                <h4>等级特权</h4>
                <div class="privilege-items">
                  <div class="privilege-item">
                    <i class="fas fa-coins"></i>
                    <span>透支限额×{{ level.overdraftMultiplier }}</span>
                  </div>
                  <div class="privilege-item">
                    <i class="fas fa-percentage"></i>
                    <span>利息{{ level.interestDiscount * 100 }}%</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="level-actions">
            <button class="edit-btn" @click="editLevel(level)">
              <i class="fas fa-edit"></i>
              编辑
            </button>
            <button class="delete-btn" @click="deleteLevel(level.id)">
              <i class="fas fa-trash"></i>
              删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增/编辑等级对话框 -->
    <div class="dialog-overlay" v-if="showAddDialog || showEditDialog" @click.self="closeDialog">
      <div class="dialog" v-if="showAddDialog" @click.stop>
        <div class="dialog-header">
          <h3>新增VIP等级</h3>
          <button class="close-btn" @click="closeDialog">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label>等级名称</label>
            <input type="text" v-model="formData.name" placeholder="如：青铜、白银、黄金">
          </div>
          <div class="form-group">
            <label>等级数值</label>
            <input type="number" v-model="formData.level" placeholder="1-5，数字越大等级越高">
          </div>
          <div class="form-group">
            <label>最低累计消费 (元)</label>
            <input type="number" v-model="formData.minTotalConsumption" placeholder="0" step="0.01">
          </div>
          <div class="form-group">
            <label>最低累计充值 (元)</label>
            <input type="number" v-model="formData.minTotalRecharge" placeholder="0" step="0.01">
          </div>
          <div class="form-group">
            <label>透支限额倍数</label>
            <input type="number" v-model="formData.overdraftMultiplier" placeholder="1.0" step="0.1">
          </div>
          <div class="form-group">
            <label>利息折扣 (0-100%)</label>
            <input type="number" v-model="formData.interestDiscount" placeholder="100" step="1">
            <small>输入0-100之间的数字，如80表示8折</small>
          </div>
          <div class="form-group">
            <label>优先级</label>
            <input type="number" v-model="formData.priority" placeholder="通常与等级数值相同">
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeDialog">取消</button>
          <button class="confirm-btn" @click="saveLevel">确定</button>
        </div>
      </div>

      <div class="dialog" v-if="showEditDialog" @click.stop>
        <div class="dialog-header">
          <h3>编辑VIP等级</h3>
          <button class="close-btn" @click="closeDialog">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label>等级名称</label>
            <input type="text" v-model="formData.name" placeholder="如：青铜、白银、黄金">
          </div>
          <div class="form-group">
            <label>等级数值</label>
            <input type="number" v-model="formData.level" placeholder="1-5，数字越大等级越高">
          </div>
          <div class="form-group">
            <label>最低累计消费 (元)</label>
            <input type="number" v-model="formData.minTotalConsumption" placeholder="0" step="0.01">
          </div>
          <div class="form-group">
            <label>最低累计充值 (元)</label>
            <input type="number" v-model="formData.minTotalRecharge" placeholder="0" step="0.01">
          </div>
          <div class="form-group">
            <label>透支限额倍数</label>
            <input type="number" v-model="formData.overdraftMultiplier" placeholder="1.0" step="0.1">
          </div>
          <div class="form-group">
            <label>利息折扣 (0-100%)</label>
            <input type="number" v-model="formData.interestDiscount" placeholder="100" step="1">
            <small>输入0-100之间的数字，如80表示8折</small>
          </div>
          <div class="form-group">
            <label>优先级</label>
            <input type="number" v-model="formData.priority" placeholder="通常与等级数值相同">
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeDialog">取消</button>
          <button class="confirm-btn" @click="updateLevel">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { rulesAPI } from '@/api/rules.js'

const router = useRouter()

const levels = ref([])
const loading = ref(false)
const showAddDialog = ref(false)
const showEditDialog = ref(false)
const editingId = ref(null)

const formData = ref({
  name: '',
  level: 1,
  minTotalConsumption: 0,
  minTotalRecharge: 0,
  overdraftMultiplier: 1.0,
  interestDiscount: 100,
  priority: 1
})

// 加载VIP等级列表
const loadLevels = async () => {
  loading.value = true
  try {
    const response = await rulesAPI.vip.getAll()
    console.log('VIP等级响应:', response)
    if (response.data && response.data.success && response.data.data) {
      levels.value = response.data.data
    } else {
      levels.value = []
    }
  } catch (error) {
    console.error('获取VIP等级失败:', error)
    alert('获取等级列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 新增等级按钮点击
const handleAddLevel = () => {
  formData.value = {
    name: '',
    level: 1,
    minTotalConsumption: 0,
    minTotalRecharge: 0,
    overdraftMultiplier: 1.0,
    interestDiscount: 100,
    priority: 1
  }
  showAddDialog.value = true
}

// 新增等级
const saveLevel = async () => {
  if (!validateForm()) return

  try {
    const submitData = {
      ...formData.value,
      interestDiscount: formData.value.interestDiscount / 100
    }
    const response = await rulesAPI.vip.create(submitData)
    if (response.data && response.data.success !== false) {
      alert('添加成功！')
      closeDialog()
      await loadLevels()
    }
  } catch (error) {
    console.error('添加等级失败:', error)
    alert('添加失败，请重试：' + (error.message || ''))
  }
}

// 编辑等级
const editLevel = (level) => {
  editingId.value = level.id
  formData.value = {
    name: level.name,
    level: level.level,
    minTotalConsumption: level.minTotalConsumption,
    minTotalRecharge: level.minTotalRecharge,
    overdraftMultiplier: level.overdraftMultiplier,
    interestDiscount: level.interestDiscount * 100,
    priority: level.priority
  }
  showEditDialog.value = true
}

// 更新等级
const updateLevel = async () => {
  if (!validateForm()) return

  try {
    const submitData = {
      ...formData.value,
      interestDiscount: formData.value.interestDiscount / 100
    }
    const response = await rulesAPI.vip.update(editingId.value, submitData)
    if (response.data && response.data.success !== false) {
      alert('更新成功！')
      closeDialog()
      await loadLevels()
    }
  } catch (error) {
    console.error('更新等级失败:', error)
    alert('更新失败，请重试')
  }
}

// 删除等级
const deleteLevel = async (id) => {
  if (!confirm('确定要删除这个VIP等级吗？')) return

  try {
    const response = await rulesAPI.vip.delete(id)
    if (response.data && response.data.success !== false) {
      alert('删除成功！')
      await loadLevels()
    }
  } catch (error) {
    console.error('删除等级失败:', error)
    alert('删除失败，请重试')
  }
}

// 初始化默认等级
const initializeLevels = async () => {
  if (!confirm('确定要初始化默认的5个VIP等级吗？这将创建青铜、白银、黄金、铂金、钻石等级。')) {
    return
  }

  try {
    const response = await rulesAPI.vip.init()
    if (response.data && response.data.success !== false) {
      alert('初始化成功！')
      await loadLevels()
    }
  } catch (error) {
    console.error('初始化失败:', error)
    alert('初始化失败，请重试')
  }
}

// 表单验证
const validateForm = () => {
  if (!formData.value.name || formData.value.name.trim() === '') {
    alert('等级名称不能为空')
    return false
  }
  if (formData.value.level < 1 || formData.value.level > 10) {
    alert('等级数值必须在1-10之间')
    return false
  }
  if (formData.value.minTotalConsumption < 0) {
    alert('最低累计消费不能为负数')
    return false
  }
  if (formData.value.minTotalRecharge < 0) {
    alert('最低累计充值不能为负数')
    return false
  }
  if (formData.value.overdraftMultiplier <= 0) {
    alert('透支限额倍数必须大于0')
    return false
  }
  if (formData.value.interestDiscount < 0 || formData.value.interestDiscount > 100) {
    alert('利息折扣必须在0-100%之间')
    return false
  }
  return true
}

// 关闭对话框
const closeDialog = () => {
  showAddDialog.value = false
  showEditDialog.value = false
  editingId.value = null
}

// 返回
const goBack = () => {
  router.push('/admin/dashboard')
}

onMounted(() => {
  loadLevels()
})
</script>

<style scoped>
.vip-management {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #666;
  padding: 5px;
  border-radius: 5px;
  transition: background 0.3s;
}

.back-btn:hover {
  background: #f0f0f0;
}

.header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.add-btn {
  background: #f39c12;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  transition: background 0.3s;
}

.add-btn:hover {
  background: #e67e22;
}

.levels-container {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 20px;
  min-height: 400px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #999;
}

.loading i {
  font-size: 48px;
  margin-bottom: 10px;
  color: #f39c12;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #999;
}

.empty-state i {
  font-size: 64px;
  margin-bottom: 15px;
  color: #f39c12;
}

.init-btn {
  background: #f39c12;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  margin-top: 20px;
  transition: background 0.3s;
}

.init-btn:hover {
  background: #e67e22;
}

.levels-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.level-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  transition: box-shadow 0.3s;
}

.level-card:hover {
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.level-content {
  flex: 1;
}

.level-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}

.level-badge {
  padding: 8px 16px;
  border-radius: 20px;
  color: white;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.level-1 { background: linear-gradient(135deg, #cd7f32, #b8732d); }
.level-2 { background: linear-gradient(135deg, #c0c0c0, #a8a8a8); }
.level-3 { background: linear-gradient(135deg, #ffd700, #e5c100); color: #333; }
.level-4 { background: linear-gradient(135deg, #e5e4e2, #c0c0c0); color: #333; }
.level-5 { background: linear-gradient(135deg, #b9f2ff, #89d4f0); color: #333; }

.level-number {
  color: #666;
  font-size: 14px;
}

.level-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-row {
  display: grid;
  grid-template-columns: repeat(2, minmax(150px, 1fr));
  gap: 15px;
}

.detail-item {
  display: flex;
  gap: 8px;
}

.detail-item .label {
  color: #666;
  font-size: 14px;
  min-width: 80px;
}

.detail-item .value {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.privileges {
  margin-top: 5px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.privileges h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 14px;
}

.privilege-items {
  display: flex;
  gap: 20px;
}

.privilege-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  font-size: 13px;
}

.privilege-item i {
  color: #f39c12;
}

.level-actions {
  display: flex;
  gap: 10px;
}

.edit-btn, .delete-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  transition: all 0.3s;
}

.edit-btn {
  background: #007bff;
  color: white;
}

.edit-btn:hover {
  background: #0056b3;
}

.delete-btn {
  background: #dc3545;
  color: white;
}

.delete-btn:hover {
  background: #c82333;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: auto;
  padding: 20px;
}

.dialog {
  background: #ffffff;
  border-radius: 10px;
  width: 100%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  z-index: 10000;
  box-shadow: 0 10px 40px rgba(0,0,0,0.3);
  animation: dialogFadeIn 0.3s ease-out;
  position: relative;
}

@keyframes dialogFadeIn {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.dialog-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #f39c12;
}

.form-group small {
  display: block;
  margin-top: 4px;
  color: #999;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #e0e0e0;
}

.cancel-btn, .confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.cancel-btn {
  background: #f0f0f0;
  color: #333;
}

.cancel-btn:hover {
  background: #e0e0e0;
}

.confirm-btn {
  background: #f39c12;
  color: white;
}

.confirm-btn:hover {
  background: #e67e22;
}

@media (max-width: 768px) {
  .detail-row {
    grid-template-columns: 1fr;
  }

  .level-card {
    flex-direction: column;
  }

  .level-actions {
    width: 100%;
    margin-top: 15px;
  }

  .privilege-items {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
